<?php
/**
 * Copyright (c) [2019] [吴跃忠]
 * [selibra] is licensed under the Mulan PSL v1.
 * You can use this software according to the terms and conditions of the Mulan PSL v1.
 * You may obtain a copy of Mulan PSL v1 at:
 * http://license.coscl.org.cn/MulanPSL
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v1 for more details.
 */

namespace Selibra\WebSocket\MessageParser;


use Selibra\WebSocket\Exceptions\EmptyMessageException;
use Selibra\WebSocket\Exceptions\MessageParsingFailedException;
use Selibra\WebSocket\MessageInput;
use Selibra\WebSocket\Protocols\MessageInputInterface;
use Selibra\WebSocket\Protocols\MessageParserInterface;

class JSONParser implements MessageParserInterface
{


    /**
     * @param string $message
     * @return MessageInputInterface
     * @throws MessageParsingFailedException
     * @throws EmptyMessageException
     */
    public function parser(string $message): MessageInputInterface
    {
        $messageInput = new MessageInput();
        $data = json_decode($message, true);
        if ((!is_array($data) || empty($data)) && !empty($message)) {
            throw new MessageParsingFailedException("Message parsing failed!");
        } elseif (!is_array($data) || empty($data)) {
            throw new EmptyMessageException();
        }
        $messageInput->setAction($data['action']);
        unset($data['action']);
        $messageInput->setData($data);
        return $messageInput;
    }
}